package com.xmltest.demo.update;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author xuehu
 * @date 2021/3/1 16:17
 */

public class Update {

    public static void main(String[] args) throws DocumentException, IOException {
        /**
         * 1.修改指定的元素
         * 前提在于查询到指定的元素
         */
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new File("java-xml/student.xml"));
        Element student = (Element) document.selectSingleNode("//student[@id='02']");
        String name = student.element("name").getText();
        System.out.println(name);
        //改属性
        student.element("name").addAttribute("type", "逗比");
        //改标签值
        student.element("name").setText("王尼玛");

        //回写
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(new FileOutputStream("src/students_copy.xml"), format);
        writer.write(document);
        writer.close();
    }

}
